using System;
using Sce.Pss.Core;
using Sce.Pss.Core.Environment;
using Sce.Pss.Core.Graphics;
using Sce.Pss.Core.Imaging;
using Sce.Pss.Core.Input;
using Sce.Pss.HighLevel.GameEngine2D;
using Sce.Pss.HighLevel.GameEngine2D.Base;

namespace CleanCodeExample
{
	public class MeineApp
	{
		private GraphicsContext graphics;
		private Scene meineScene;
		private SpriteUV spriteBlau;
		
		public AppZustand ZustandDerApp {get;set;}
		
		protected FpsUeberwacher FpsUeberwacherInstanz{get;set;} 		
		
		public MeineApp ()
		{
			ZustandDerApp = AppZustand.Init;			
		}

		void SceneErzeugen ()
		{
			meineScene = new Scene();
			meineScene.Camera.SetViewFromViewport();
			
			TextureInfo textureInfo = LoadTexture(@"/Application/grafik/blue.png");
			
			spriteBlau = new SpriteUV(textureInfo);
			spriteBlau.Quad.S = new Vector2(50,50);
			spriteBlau.Position = new Vector2(400,200);
			
			meineScene.AddChild(spriteBlau);
		}
		
		public void Initialize ()
		{
			// Set up the graphics system
			graphics = new GraphicsContext ();			
			
			FpsUeberwacherInstanz = new FpsUeberwacher(FpsMoeglichkeiten.Fps60);
			
			Director.Initialize(5000, 100, graphics); 
			
			Director.Instance.GL.Context.SetClearColor(Colors.Red);

			SceneErzeugen ();
			
			Director.Instance.RunWithScene(meineScene, true);
		}

		public void StartRunning()
		{
			// Set up the graphics system
			if (ZustandDerApp!=AppZustand.Init)
			{
				throw new ArgumentException("App im falschen Zustand!");	
			}
			ZustandDerApp = AppZustand.AppRunning;
		}
		
		public void Wait()
		{
			FpsUeberwacherInstanz.WarteFuerSync();	
		}
		
		public void Update ()
		{
			// Query gamepad for current state
			var gamePadData = GamePad.GetData (0);
			
			if (gamePadData.IstLgedrueckt())
			{
				ZustandDerApp = AppZustand.EndApp;	
			}
			Vector2 position = spriteBlau.Position;
			
			if (gamePadData.IstDigitalNachObenGedrueckt())
			{
				position = new Vector2(position.X, position.Y + 1);
			}
			if (gamePadData.IstDigitalNachUntenGedrueckt())
			{
				position = new Vector2(position.X, position.Y - 1);
			}
			if (gamePadData.IstDigitalNachRechtsGedrueckt())
			{
				position = new Vector2(position.X+1, position.Y);
			}
			if (gamePadData.IstDigitalNachLinksGedrueckt())
			{
				position = new Vector2(position.X-1, position.Y);
			}
			spriteBlau.Position = position;
			
			Director.Instance.Update();			
		}

		public void Render ()
		{
			Director.Instance.Render();
			Director.Instance.GL.Context.SwapBuffers();
			Director.Instance.PostSwap();
		}
		
		internal static TextureInfo LoadTexture(string filename)
		{
			return new TextureInfo(new Texture2D(filename, false));
		}			
	}
}

